package com.sf.dlb.utils;

import com.sf.dlb.constant.ResponseConstant;
import com.sf.dlb.vo.ResultVO;
import org.apache.http.*;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * http工具类
 *
 * Created by jing.tan on 2018/5/21.
 */
public class HttpClientUtils {

	private static Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);

	/**
	 * post发送json
	 * @param url
	 * @param jsonString
	 * @return
	 */
	public static String postJson(String url, String jsonString) {
		CloseableHttpClient httpClient = null;
		StringBuffer sb = new StringBuffer("");
		try {
			httpClient = HttpClients.createDefault();
			HttpPost request = new HttpPost(url);

			StringEntity params = new StringEntity(jsonString, "UTF-8");
			request.addHeader("content-type", "application/json");
			request.setEntity(params);
			request.releaseConnection();
			HttpResponse response = httpClient.execute(request);

			// 打印服务器返回的状态
			logger.info(" 返回的状态," + response.getStatusLine());

			HttpEntity entity = response.getEntity();
			InputStream instream = entity.getContent();
			BufferedReader in = new BufferedReader(new InputStreamReader(instream, "UTF-8"));
			sb = new StringBuffer();
			String line;
			while (null != (line = in.readLine())) {
				sb.append(line).append("\n");
			}
			logger.info(" 请求返回的json," + sb.toString());
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("请求返回状态异常." + e.getLocalizedMessage());
		} finally {
			try {
				if (httpClient != null) {
					httpClient.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
				logger.error(e.getLocalizedMessage());
			}
		}
		return sb.toString();
	}

	/**
	 * post发送json + header信息设置
	 * */
	public static String postJsonAddHeader(String url, String jsonString, Map<String, String> headers) {
		CloseableHttpClient httpClient = null;
		StringBuffer sb = new StringBuffer("");
		try {
			httpClient = HttpClients.createDefault();
			HttpPost request = new HttpPost(url);
			StringEntity params = new StringEntity(jsonString, "UTF-8");
			request.addHeader("content-type", "application/json");
			for (String key : headers.keySet()) {
				request.addHeader(key, headers.get(key));
			}
			request.setEntity(params);
			request.releaseConnection();

			HttpResponse response = httpClient.execute(request);

			// 打印服务器返回的状态
			logger.info(" 返回的状态," + response.getStatusLine());

			HttpEntity entity = response.getEntity();
			InputStream instream = entity.getContent();
			BufferedReader in = new BufferedReader(new InputStreamReader(instream, "UTF-8"));
			sb = new StringBuffer();
			String line;
			while (null != (line = in.readLine())) {
				sb.append(line).append("\n");
			}
			logger.info(" 请求返回的json," + sb.toString());
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("请求返回状态异常." + e.getLocalizedMessage());
		} finally {
			try {
				if (httpClient != null) {
					httpClient.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
				logger.error(e.getLocalizedMessage());
			}
		}
		return sb.toString();
	}
	/**
	 * Post From请求
	 *
	 * @param url   资源地址
	 * @param map   参数列表
	 * @return
	 */
	public static HttpResponse postFrom(String url, Map<String,String> map){
		logger.info("postFrom请求地址："+url);
		logger.info("请求参数："+GsonUtils.getInstance().toJson(map));
		//创建httpclient对象
		CloseableHttpClient client = HttpClients.createDefault();
		//创建post方式请求对象
		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build();//设置请求和传输超时时间
		HttpPost httpPost = new HttpPost(url);
		httpPost.setConfig(requestConfig);
		//装填参数
		List<NameValuePair> nvps = new ArrayList<>();
		if(map!=null){
			for (Map.Entry<String, String> entry : map.entrySet()) {
				nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
			}
		}
		HttpResponse response=null;
		try {
			//设置参数到请求对象中
			httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
			//设置header信息
			//指定报文头【Content-type】、【User-Agent】
			httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
			httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
			//执行请求操作，并拿到结果（同步阻塞）
			response = client.execute(httpPost);
//			int statusCode=response.getStatusLine().getStatusCode();
//			HttpEntity entity = response.getEntity();
//
//			String body = "";
//			if(statusCode==200){
//				if (entity != null) {
//					//按指定编码转换结果实体为String类型
//					body = EntityUtils.toString(entity, "utf-8");
//					return ResultVOUtil.success(body);
//				}
//			}
//			logger.info("postFrom statusCode is == "+statusCode);
//			logger.info("postFrom body is == "+body);
		}catch (Exception e){
			logger.info("postFrom body is errer");
			e.printStackTrace();
		}
		return response;
	}
	/**
	 * get From请求
	 *
	 * @param url   资源地址
	 * @return
	 */
	public static HttpResponse getFrom(String url){
		return getFromAndHeader(url,null);
	}

	/**
	 * get From请求
	 *
	 * @param url   资源地址
	 * @return
	 */
	public static HttpResponse getFromAndHeader(String url,Map<String, String> headers){
		logger.info(" getFrom 请求的url=" + url);
		CloseableHttpClient httpCilent = HttpClients.createDefault();
		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build();//设置请求和传输超时时间
		HttpGet httpGet = new HttpGet(url);
		httpGet.setConfig(requestConfig);
		if(null!=headers){
			for (String key : headers.keySet()) {
				httpGet.addHeader(key, headers.get(key));
			}
		}
		HttpResponse response=null;
		try {
			response = httpCilent.execute(httpGet);
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("getFrom body is errer");
		}
		return response;
	}


	public static void main(String[] args){

	}
}
